package main

import (
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"server/biz"
	"server/biz/proto"
	"time"

	urfave "github.com/urfave/cli/v2"
)

func ToGB(b int64) float64 {
	f := float64(b)
	return f / 1024 / 1024 / 1024
}

// 返回false终止任务, true继续任务
func doonce(bot_id string) bool {
	t, err := AskTask(bot_id)
	if err != nil {
		log.Println("请求任务失败:", err)
		time.Sleep(time.Second * 10)
		return true
	}
	if t == nil {
		log.Println("暂无任务")
		time.Sleep(time.Second * 10)
		return true
	}
	log.Println("新的任务>>>>:", t.OrderId, t.Id, "进度:", t.Progress, "/", t.Total)
	err = Copy(t)
	if err != nil {
		log.Println("拷贝失败:", t.OrderId, t.Id, err)
		if e := FinTask(t, err.Error()); e != nil {
			log.Println("FinTask err:", e)
		}
		return false
	} else {
		if e := FinTask(t, ""); e != nil {
			log.Println("FinTask err:", e)
			return false
		}
		log.Println("提交任务成功:", t.OrderId, t.Id)
		return true
	}
}

// 返回(下一轮延迟, error)
func Copy(t *proto.Task) error {
	if t.Src == "" {
		return errors.New("来源路径为空")
	}
	if t.Dst == "" {
		return errors.New("目标路径为空")
	}

	srcstat, err := os.Stat(t.Src)
	if err != nil {
		return err
	}
	if srcstat.Mode().IsDir() {
		_, d := filepath.Split(t.Src)
		dst := filepath.Join(t.Dst, d)
		err := CopyDir(t.Src, dst)
		if err != nil {
			return err
		}
	} else {
		if !srcstat.Mode().IsRegular() {
			return errors.New("来源文件不是正规文件")
		}
		//dststat, err := os.Stat(t.Dst)
		//if err != nil {
		//	return err
		//}
		//if !dststat.IsDir() {
		//	return errors.New("目标路径必须是目录")
		//}
		err = CopyFile(t.Src, t.Dst)
		if err != nil {
			return err
		}
	}
	log.Println("已考完:", t.Id, "任务大小:", t.Size)
	return nil
}

var cmdRun = &urfave.Command{
	Name:  "run",
	Usage: "正式运行",
	Flags: []urfave.Flag{
		&urfave.StringFlag{Name: "id", Usage: "", Required: false},
	},
	Action: func(cctx *urfave.Context) error {
		fmt.Println("API HOST4:", HOST)
		bot_id := cctx.String("id")
		for bot_id == "" {
			fmt.Print("请输入BOT_ID: ")
			fmt.Scanln(&bot_id)
		}
		fmt.Println("bot_id:", bot_id)
		for {
			doonce(bot_id)
		}
		return nil
	},
}

var cmdCheck = &urfave.Command{
	Name:  "check",
	Usage: "预检ps4.excel和待处理订单的包和本地是否一致",
	Flags: []urfave.Flag{
		&urfave.StringFlag{
			Name:    "excel",
			Aliases: []string{"x"},
			Value:   "./总和.xlsx",
		},
	},
	Action: func(cctx *urfave.Context) error {
		fmt.Println("API HOST4:", HOST)
		fmt.Println("开始检测excel文件完整性...")
		filename := cctx.String("excel")
		{
			err := biz.CheckExcel(filename)
			if err != nil {
				return err
			}
		}
		fmt.Println("开始检测订单文件完整性...")
		{
			err := CheckWaitingPkgs()
			if err != nil {
				return err
			}
		}
		fmt.Println("检测OK! 可以提交excel.")
		return nil
	},
}

func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)

	local := []*urfave.Command{
		cmdRun,
		cmdCheck,
	}

	app := &urfave.App{
		Name:                 "cpbot",
		Usage:                "拷贝机器人",
		Version:              "0.3",
		EnableBashCompletion: true,
		Flags:                []urfave.Flag{},

		Commands: local,
	}
	app.Setup()

	args := os.Args
	// default command: run
	if len(args) == 1 {
		args = append(args, "run")
	}
	if err := app.Run(args); err != nil {
		panic(err)
	}
}
